<?php

namespace App\Http\Requests\Admin\CollArea;
use App\Http\Requests\Request;
use App\Models\Common\CollArea;
use Illuminate\Support\Facades\Validator;

class CreateRequest extends Request {
    public function authorize(){
        return true;
    }
    public function rules(){
        //添加省份地区排序判断
        Validator::extend('check_area_sort', function($attribute, $value, $parameters) {
            if($value!=0){
                if($this->grade == '2'){
                    $areaSort = CollArea::where('grade','2')->where('pid',$this->pid)->pluck('sort')->toArray();
                    if(in_array($value,$areaSort)){
                        return false;
                    }else{
                        return true;
                    }
                }else if($this->grade == '3'){
                    $citySort = CollArea::where('grade','3')->where('pid',$this->pid)->pluck('sort')->toArray();
                    if(in_array($value,$citySort)){
                        return false;
                    }else{
                        return true;
                    }
                }
            }else{
                return true;
            }
        });


        $input = $this->all();
        return [
            'name'=>'required',
            'cid'=>'required|numeric|max:999999|unique:coll_area,cid|cid_match:'.$input['grade'].','.$input['pid'],
            'sort'=>'check_area_sort'
        ];
    }
    public function messages(){
        $input = $this->all();
        $cid_match = '';
        if($input['grade'] == '2'){
            $two = substr($input['pid'],0,2);
            $end = '00';
            $cid_match = '地区编码必须以'.$two.'开头，'.$end.'结尾的6位数数字组合';
            $sort = '地区编码排序值已经存在';
        }else if($input['grade'] == '3'){
            $three = substr($input['pid'],0,4);
            $cid_match = '城市编码必须以'.$three.'开头的6位数数字组合';
            $sort = '城市编码排序值已经存在';
        }
        return [
            'name.required'=>'地区名称必须填写',
            'cid.required'=>'地区编码必须填写',
            'cid.unique'=>'地区编码已经存在',
            'cid.numeric'=>'地区编码必须是一个数字',
            'cid.max'=>'地区编码必须是一个6数字',
            'cid.cid_match'=>$cid_match,
            'sort.check_area_sort'=>$sort
        ];
    }
}
